package helper

import (
	"fmt"
	"strconv"
	"strings"
	"time"
)

const (
	TimeFormart = "2006-01-02 15:04:05"
	TimeFormart2 = "2006-01-02 15:04:05.999"
)

type C_Datetime time.Time
type C_float32 float32
type C_int int
type C_int32 int32

func (t C_Datetime) MarshalJSON() ([]byte, error) {
	var stamp = fmt.Sprintf("\"%s\"", time.Time(t).Format("2006-01-02 15:04:05"))
	return []byte(stamp), nil
}

func (t C_Datetime) Format(format string) string {
	t2 := time.Time(t)
	return t2.Format(format)
}

func (t C_Datetime) Unix() int64 {
	t2 := time.Time(t)
	unix := t2.Unix()
	return unix
}

func (t C_Datetime) Before(u time.Time) bool {
	return time.Time(t).Before(u)
}

func (t C_Datetime) After(u time.Time) bool {
	return time.Time(t).After(u)
}

func (t C_Datetime) Equal(u time.Time) bool {
	return time.Time(t).Equal(u)
}

func (t C_Datetime) EqualMinTime() bool {
	parse, _ := time.Parse(TimeFormart, "1900-01-01 00:00:00")
	var isMinTime = time.Time(t).Before(parse)
	return isMinTime
}

var LOC, _ = time.LoadLocation("Asia/Shanghai")

func (t *C_Datetime) UnmarshalJSON(data []byte) (err error) {
	value := string(data)
	if value == "" {
		return nil
	}
	if value == "\"\"" {
		return nil
	}
	if value == "\"string\"" {
		return nil
	}
	value = strings.Replace(value, "T", " ", -1)
	value = value[1:20]
	now, err := time.ParseInLocation(TimeFormart, value, time.Local)

	if err != nil {
		*t = C_Datetime(now)
		return
	}
	*t = C_Datetime(now)
	return
}

func (t C_Datetime) Now() C_Datetime {
	return C_Datetime(time.Now())
}

func Now() C_Datetime {
	return C_Datetime(time.Now())
}

func (t *C_float32) UnmarshalJSON(data []byte) (err error) {
	value := string(data)
	value = strings.ReplaceAll(value, "\"", "")
	if value == "" || value == "0" || value == "string" {
		*t = 0
		return nil
	}
	f, _ := strconv.ParseFloat(value, 32) //string转float32
	*t = C_float32(f)
	return nil
}

func (t *C_int) UnmarshalJSON(data []byte) (err error) {
	value := string(data)
	value = strings.ReplaceAll(value, "\"", "")
	if value == "" || value == "0" || value == "string" {
		*t = 0
		return nil
	}
	f, _ := strconv.Atoi(value)
	*t = C_int(f)
	return nil
}
func (t *C_int32) UnmarshalJSON(data []byte) (err error) {
	value := string(data)
	value = strings.ReplaceAll(value, "\"", "")
	if value == "" || value == "0" || value == "string" {
		*t = 0
		return nil
	}
	f, _ := strconv.Atoi(value)
	*t = C_int32(f)
	return nil
}
